Categories
React Hooks

Top React Hooks — Async, Clipboard, and Cookie

Spread the love

Hooks contains our logic code in our React app.

We can create our own hooks and use hooks provided by other people.

In this article, we’ll look at some useful React hooks.

react-use

The react-use library is a big library with many handy hooks.

useAsyncRetry

The useAsyncRetry hook lets us run async cod with an addition rety method to let us retry or refresh the async function.

To use it, we run:

import React from "react";
import { useAsyncRetry } from "react-use";

export default function App() {
  const state = useAsyncRetry(async () => {
    const response = await fetch("https://api.agify.io/?name=michael");
    const result = await response.json();
    return result;
  }, []);

  return (
    <div>
      <button onClick={() => state.retry()}>load</button>
      {(() => {
        if (state.loading) {
          return <div>Loading...</div>;
        }

        if (state.error) {
          return <div>Error</div>;
        }

        return <div>{JSON.stringify(state.value)}</div>;
      })()}
    </div>
  );
}

The useAsyncRetry hook takes a callback that gets data from an API.

A promise is returned and it resolves to the response body.

The state is returned by the hook.

It has the retry method to let us get the data again.

Also, it has the loading and error properties to get the loading state and error respectively.

value has the response body.

useBeforeUnload

The useBeforeUnload hook lets us show a browser alert when the user tries to reload or close the page.

To use it, we can write:

import React from "react";
import { useBeforeUnload } from "react-use";

export default function App() {
  useBeforeUnload(true, "You sure you want to leave");

  return <div />;
}

We pass in true to the first argument to enable the alert when we leave.

Then we add a string to show the content.

Most browsers don’t let us show custom text in the alert, so we can put in anything.

useCookie

useCookie is a hook that lets us return the current value of a cookie.

It also lets us update and delete the cookie.

For instance, we can use it by writing:

import React from "react";
import { useCookie } from "react-use";

export default function App() {
  const [value, updateCookie, deleteCookie] = useCookie("count-cookie");
  const [counter, setCounter] = React.useState(1);

  React.useEffect(() => {
    deleteCookie();
  }, []);

  const updateCookieHandler = () => {
    updateCookie(counter);
    setCounter(c => c + 1);
  };

  return (
    <div>
      <p>Value: {value}</p>
      <button onClick={updateCookieHandler}>Update Cookie</button>
      <br />
      <button onClick={deleteCookie}>Delete Cookie</button>
    </div>
  );
}

We call the useCookie hook with the key of the cookie to let us get, set, and delete the cookie.

value has the value.

updateCookie is a function to let us update the cookie.

deleteCookie lets us delete the cookie.

Then we used that in the useEffect callback to clear the cookie on load.

And we used updateCookie when we click the Update Cookie button.

useCopyToClipboard

The useCopyToClipboard hook lets us copy text in a string to the clipboard.

For instance, we can use it by writing:

import React from "react";
import { useCopyToClipboard } from "react-use";

export default function App() {
  const [text, setText] = React.useState("");
  const [state, copyToClipboard] = useCopyToClipboard();

  return (
    <div>
      <input value={text} onChange={e => setText(e.target.value)} />
      <button type="button" onClick={() => copyToClipboard(text)}>
        copy text
      </button>
      {state.error ? (
        <p>{state.error.message}</p>
      ) : (
        state.value && <p>Copied {state.value}</p>
      )}
    </div>
  );
}

We called the useCopyToClipboard hook to return the state and copyToClipboard variables.

state is the state of the clipboard.

copyToClipboard lets us copy the text we pass into it to the clipboard.

Conclusion

The react-use library provides us with hooks to copy data to the clipboard, create cookies, and run promises.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *